import { action, makeObservable } from 'mobx';

import { storageInfo, storageToken, storageAuthority } from 'Configs/common';
import WithCreateForm from 'Core/common/WithCreateForm';
// import SliderCaptchaStore from 'Core/SliderCaptchaStore';
import LoginModel, { LoginDataIndex } from 'Models/Login';

export type MessageLoginFormData = Partial<
    Pick<
        LoginModel,
        | LoginDataIndex.ACCOUNT
        | LoginDataIndex.PASSWORD
        | LoginDataIndex.REMEMBER
        | LoginDataIndex.PHONE
        | LoginDataIndex.CAPTCHA
    >
>;

class LoginStore extends WithCreateForm<MessageLoginFormData> {
    // @observable [LoginDataIndex.SLIDER_CAPTCHA_STORE]: SliderCaptchaStore = new SliderCaptchaStore();

    constructor() {
        super();

        makeObservable(this);
    }

    @action getInfoFromLocalStorage = (): MessageLoginFormData => {
        let form = {} as MessageLoginFormData;

        const info = localStorage.getItem(storageInfo) as string;
        if (typeof info === 'string') {
            try {
                const account = JSON.parse(info) as MessageLoginFormData;

                if (typeof account === 'object')
                    form = {
                        ...account,
                        [LoginDataIndex.PASSWORD]: account.password && window.atob(account.password),
                    };
            } catch (e) {
                // this.removeLocalStorageToken();
            }
        }

        return form;
    };

    @action saveInfoToLocalStorage = () => {
        const {
            [LoginDataIndex.REMEMBER]: remember,
            [LoginDataIndex.ACCOUNT]: account,
            [LoginDataIndex.PASSWORD]: password,
        } = this.createFormData;

        localStorage.setItem(
            storageInfo,
            JSON.stringify({
                remember,
                account,
                password: password && window.btoa(password), // base64 encryption
            }),
        );
    };

    @action removeLocalStorageInfo = () => localStorage.removeItem(storageInfo);

    @action saveTokenToLocalStorage = (token: string) => localStorage.setItem(storageToken, token);

    @action saveAuthorityToLocalStorage = (authority: string) => localStorage.setItem(storageAuthority, authority);

    @action removeLocalStorageAuthority = () => localStorage.removeItem(storageAuthority);

    @action removeLocalStorageToken = () => {
        localStorage.removeItem(storageToken);
    };
}

export default LoginStore;
